<template>
  <el-card class="user-profile">
    <el-form :model="user" label-width="120px">
      <el-form-item label="头像">
        <el-upload
          class="avatar-uploader"
          action="https://jsonplaceholder.typicode.com/posts/"
          :show-file-list="false"
          :before-upload="beforeAvatarUpload"
        >
          <img v-if="user.photo" :src="user.photo" class="avatar" />
          <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
        </el-upload>
      </el-form-item>
      <el-form-item label="用户ID">
        <el-input v-model="user.id" />
      </el-form-item>
      <el-form-item label="用户名">
        <el-input v-model="user.name" />
      </el-form-item>
      <el-form-item label="真实姓名">
        <el-input v-model="user.real_name" />
      </el-form-item>
      <el-form-item label="性别">
        <el-radio-group v-model="user.gender">
          <el-radio label="0">男</el-radio>
          <el-radio label="1">女</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="生日">
        <el-date-picker
          v-model="user.birthday"
          type="date"
          placeholder="选择日期"
          format="YYYY-MM-DD"
          value-format="YYYY-MM-DD"
        />
      </el-form-item>
      <el-form-item label="个人介绍">
        <el-input v-model="user.intro" type="textarea" />
      </el-form-item>
    </el-form>
  </el-card>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import type { UploadRawFile } from 'element-plus'

interface User {
  id: string
  name: string
  photo: string
  gender: string
  birthday: string
  real_name: string
  intro: string
}

const user = ref<User>({
  id: '',
  name: '',
  photo: '',
  gender: '',
  birthday: '',
  real_name: '',
  intro: '',
})

onMounted(() => {
  // 这里可以模拟从后端获取用户数据
  user.value = {
    id: '12345',
    name: 'username',
    photo: 'https://via.placeholder.com/100',
    gender: '0',
    birthday: '2018-12-20',
    real_name: '真实姓名',
    intro: '这是一个个人介绍示例。',
  }
})

const beforeAvatarUpload = (file: UploadRawFile) => {
  const isJPG = file.type === 'image/jpeg'
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isJPG) {
    ElMessage.error('上传头像图片只能是 JPG 格式!')
  }
  if (!isLt2M) {
    ElMessage.error('上传头像图片大小不能超过 2MB!')
  }
  return isJPG && isLt2M
}
</script>
<style scoped>
.user-profile {
  width: 80vw;
  height: 80vh;
  margin: 0 auto;
  padding: 20px;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  line-height: 100px;
  text-align: center;
}

.avatar {
  width: 100px;
  height: 100px;
  display: block;
}
</style>
